#coding=utf-8
from django.shortcuts import render, render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.http import HttpRequest
from blog.models import BlogPost
from django.template import loader
from django import forms
from blog.models import User
from django.views.decorators.csrf import csrf_exempt
from django.template import RequestContext

import os

# Create your views here.

def archive(request):
    posts = BlogPost.objects.all()
    t = loader.get_template('archive.html')
    c = {'posts':posts}
    return HttpResponse(t.render(c))

def archive_id(request, request_id):
    posts = BlogPost.objects.filter(id = request_id)
    t = loader.get_template('archive.html')
    c = {'posts':posts}
    return HttpResponse(t.render(c))

def goto(request):
    dict = request.GET.dict()
    where = dict[u'where']
    print(str(where))
    if where == u'blog':
        return archive(request)
    else:
        return HttpResponse("Hello, world. You're at the blog index.")

#表单
class UserForm(forms.Form):
    username = forms.CharField(label='用户名',max_length=20)
    password = forms.CharField(label='密码',widget=forms.PasswordInput())

class UploadForm(forms.Form):
    #title = forms.CharField
    uploadFile = forms.FileField()

# 注册页面
def register(request):
    if request.method == 'POST':
        uf = UserForm(request.POST)
        if uf.is_valid():
            #获得表单数据
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']
            #检查时候用户名已经存在
            query_set = User.objects.filter(username= username)
            print(str(query_set))
            if query_set:
                reason = "username " + username + " has been occupied!"
                print(reason)
                return HttpResponse(reason)
            else:
                print("username " + username + " is valie")
                # 添加到数据库
                User.objects.create(username = username, password = password)
                # 注册成功，跳转index
                template = loader.get_template('goindex.html')
                ctx = {'title': 'Regisger', 'info': 'Register success!!'}
                response = HttpResponse(template.render(ctx))
                # 将username写入浏览器cookie,失效时间为3600
                response.set_cookie('username', username, 3600)
                return response
        else:
            return HttpResponse('Register failed!!')
    else:
        uf = UserForm()
        #return render_to_response('register.html',  context=RequestContext(request, {'uf':uf}))
        return render(request, 'register.html', {'uf':uf})

# 登录
def login(request):
    if request.method == 'POST':
        uf = UserForm(request.POST)
        if uf.is_valid():
            #获取表单用户密码
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']
            #获取的表单数据与数据库进行比较
            #user = User.objects.filter(username__exact = username,password__exact = password)
            user = User.objects.filter(username=username)
            if user:
                if User.objects.filter(username = username, password = password):
                    # 比较成功，跳转index
                    template = loader.get_template('goindex.html')
                    ctx = {'title':'Login', 'info':'Login success!!'}
                    response = HttpResponse(template.render(ctx))
                    # 将username写入浏览器cookie,失效时间为3600
                    response.set_cookie('username', username, 3600)
                    return response
                else:
                    return HttpResponse("Password is wrong!!")
            else:
                #比较失败，还在login
                return HttpResponse("The user name does not exist!!")
    else:
        uf = UserForm()
        return render(request, 'login.html', {'uf':uf})

# 打开主页
def index(request):
    # 尝试获取cookie中的户名信息
    username = request.COOKIES.get('username', '')
    t = loader.get_template('index.html')
    c = {'username': username}
    return HttpResponse(t.render(c))

# 退出
def logout(req):
    # 比较成功，跳转index
    template = loader.get_template('goindex.html')
    ctx = {'title': 'Logout', 'info': 'Logout success!!'}
    response = HttpResponse(template.render(ctx))
    #清理cookie里保存username
    response.delete_cookie('username')
    return response

# 上传文件
def upload(request):
    if request.method == 'POST':
        # 尝试获取cookie中的户名信息
        username = request.COOKIES.get('username', '')
        if (username):
            uf = UploadForm(request.POST, request.FILES)
            if uf.is_valid():
                # HttpRequest.FILES是MultiValueDict对象
                # 获取UploadedFile对象
                uploadedFile = request.FILES['uploadFile']
                # 创建用户路径
                dir = username
                if not os.path.exists(dir):
                    os.mkdir(dir)
                # 拼接保存路径名
                filepath = os.path.join(dir, uploadedFile.name)
                # 覆盖原有文件
                if os.path.exists(filepath):
                    os.unlink(filepath)
                # 写入本地文件
                with open(filepath, 'wb+') as f:
                    for chunk in uploadedFile.chunks():
                        f.write(chunk)
                return HttpResponse("上传成功!!")
            else:
                print("Form is not valid!")
        else:
            return HttpResponse("请先登录!!")
    else:
        uf = UploadForm()
        return render(request, 'upload.html', {'uf':uf})

# 打开主页
def editblog(request):
    t = loader.get_template('blogeditor.html')
    c = {}
    return HttpResponse(t.render(c))

@csrf_exempt
def test(request):
    # 尝试获取cookie中的户名信息
    print("-----------------------------------------")
    print(">> request path = " + request.path + ", method = " + request.method)
    # for kv in request.META.items():
    #     print("{}: {}".format(kv[0], kv[1]))
    print(">> request body = " + str(request.body,'utf-8'))
    if len(request.body) > 0:
        response = HttpResponse(request.body.decode())
    else:
        response = HttpResponse()
    response['SERVER_HEADER_TEST'] = "OK"
    return response
